import angular from 'angular';
//import _ from 'lodash';

export class SuggestionsCtrl {
  navModel: any;
  cpuCores: number;
  memorySize: number;
  suggestions: any;
  errorMessages: string;

  //snapshots: any;

  /** @ngInject */
  constructor(/*private $rootScope, private backendSrv,*/$scope, navModelSrv) {
    this.navModel = navModelSrv.getNav('dashboards', 'suggestions', 0);
    this.cpuCores = 4;
    this.memorySize = 32;
    this.errorMessages = "";
  }

  updateSuggestions() {
    let vm = this;
    if (vm.validate(vm)) {
      vm.update(vm);
    }
  }

  /**
   * cpu范围设置为0-1024，内存范围设置为0-5120
   *
   * @param vm 当前的 controller 对象
   */
  validate(vm) {
    vm.errorMessages = "";

    if (vm.cpuCores === undefined) {
      vm.errorMessages += "“CPU 核数”必须从 0 到 1024！ ";
    } else if (vm.cpuCores < 0) {
      vm.errorMessages += "“CPU 核数”必须大于 0！ ";
    } else if (vm.cpuCores > 1024) {
      vm.errorMessages += "“CPU 核数”必须小于或等于 1024！ ";
    }

    if (vm.memorySize === undefined) {
      vm.errorMessages += "“内存大小（GB）”必须从 0 到 5120！";
    } else if (vm.memorySize < 0) {
      vm.errorMessages += "“内存大小（GB）”必须大于 0！";
    } else if (vm.memorySize > 5120) {
      vm.errorMessages += "“内存大小（GB）”必须小于或等于 5120！";
    }

    if (!vm.errorMessages) {
      return true;
    }

    return false;
  }

  /**
   * @see {https://trello-attachments.s3.amazonaws.com/5b07ed673789d5f350b7e849/5b7d2808abd8317b9611e2af/165356fc2495f71f7bd5fd9e8fff9421/rules.png}
   * @param vm 当前的 controller 对象
   */
  update(vm) {
    /**
     * @see 优化建议展示项
     */
    vm.suggestions = {
      "数据库": { "CPU": {}, "内存": {} },
      "操作系统": { "Linux": {}, "AIX": {} }
    };


    if (vm.cpuCores < 256) {
      vm.suggestions["数据库"]["CPU"]["PARALLEL_MAX_SERVERS"] = vm.cpuCores * 2;
    } else {
      vm.suggestions["数据库"]["CPU"]["PARALLEL_MAX_SERVERS"] = vm.cpuCores;
    }

    if (vm.cpuCores < 4) {
      vm.suggestions["数据库"]["CPU"]["gcs_server_processes"] = 1;
    } else if (vm.cpuCores <= 16) {
      vm.suggestions["数据库"]["CPU"]["gcs_server_processes"] = 2;
    } else {
      vm.suggestions["数据库"]["CPU"]["gcs_server_processes"] = 2 + vm.cpuCores / 32;
    }

    vm.suggestions["数据库"]["CPU"]["FAST_START_PARALLEL_ROLLBACK"] = "LOW";

    vm.suggestions["数据库"]["内存"] = {
      "SGA_TARGET": Math.floor(vm.memorySize * 0.8 * 0.6) + " GB",
      "SGA_MAX_SIZE": Math.floor(vm.memorySize * 0.8 * 0.6) + " GB",
      "MEMORY_MAX_TARGET": Math.floor(vm.memorySize * 0.8) + " GB",
      "MEMORY_TARGET": Math.floor(vm.memorySize * 0.8) + " GB",
    };

    vm.suggestions["操作系统"]["Linux"]["kernel.shmmax"] = Math.round(vm.memorySize * 0.8 * 0.6 * 1024 * 1024 * 1024) + " B",

    vm.suggestions["操作系统"]["AIX"] = {
      "maxperm%": "20% 按系统具体的应用设置，纯数据库服务器，应在50%以下，而对数据抽取和文件操作较多的系统，应适当调大",
      "maxclient%": "20% 按系统具体的应用设置，纯数据库服务器，应在50%以下，而对数据抽取和文件操作较多的系统，应适当调大"
    };
  }
}

angular.module('grafana.controllers').controller('SuggestionsCtrl', SuggestionsCtrl);
